package com.i8office.android.zhihuixinwu.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cyan.tools.annotation.ActivityFragmentInject;
import com.cyan.tools.base.BaseActivity;
import com.cyan.tools.util.RxBus;
import com.example.menhoo.toollibrary.common.assist.IMEHelper;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.bean.Empl;
import com.i8office.android.zhihuixinwu.bean.NotifyTarget;
import com.i8office.android.zhihuixinwu.bean.SendTarget;
import com.i8office.android.zhihuixinwu.bean.TabItem;
import com.i8office.android.zhihuixinwu.bean.WorkSheet;
import com.i8office.android.zhihuixinwu.module.contract.AddOpinionContract;
import com.i8office.android.zhihuixinwu.module.presenter.AddOpinionPresenter;
import com.i8office.android.zhihuixinwu.ui.dep.OfficeNewActivity;
import com.i8office.android.zhihuixinwu.widget.AddActionProvider;
import com.socks.library.KLog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.Main;
import application.AppApplication;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import tools.ToastUtil;

@ActivityFragmentInject(
        contentViewId = R.layout.activity_suggestion,
        toolbarTitle = R.string.sign_suggestion
)
public class SuggestionActivity extends BaseActivity<AddOpinionContract.Presenter> implements AddOpinionContract.View {
    @BindView(R.id.opinion)
    EditText opinion;
    @BindView(R.id.tabLayout)
    SegmentTabLayout tabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.submit)
    View submit;
    String titles[] = {"常用意见模板", "个人意见模板"};
    Observable<String> observable;
    Disposable disposable;
    WorkSheet workSheet;
    List<OpinionFragment> fragments = new ArrayList<>();
    private Empl empl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
        workSheet = (WorkSheet) getIntent().getSerializableExtra("workSheet");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        OpinionFragment fragment1 = new OpinionFragment();
        Bundle bundle1 = new Bundle();
        fragment1.setArguments(bundle1);
        fragments.add(fragment1);

        OpinionFragment fragment2 = new OpinionFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putBoolean("is_private", true);
        fragment2.setArguments(bundle2);
        fragments.add(fragment2);

        initViewPager();
        mPresenter = new AddOpinionPresenter(this);
        observable = RxBus.get().register("add_opinion", String.class);
        disposable = observable.subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                opinion.setText(s);
                opinion.setSelection(s.length());
            }
        });
    }

    //获取Tab
    private void initViewPager() {
        tabLayout.setTabData(titles);
        tabLayout.setVisibility(View.VISIBLE);
        ArrayList<TabItem> tabItems = new ArrayList<TabItem>();
        tabItems.add(new TabItem("1"));
        tabItems.add(new TabItem("2"));
        viewpager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }

            @Override
            public int getCount() {
                return titles.length;
            }
        });
        setupWithViewPager();
    }

    private void setupWithViewPager() {
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewpager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.add, menu);
        MenuItem item = menu.getItem(0);
        AddActionProvider addActionProvider = (AddActionProvider) MenuItemCompat.getActionProvider(item);
        addActionProvider.setOnAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String option = opinion.getText().toString().trim();
                if (TextUtils.isEmpty(option)) {
                    return;
                }
                IMEHelper.hideIME(SuggestionActivity.this, true);
                showAddOptionDialog();
            }
        });
        return true;
    }

    private void showAddOptionDialog() {
        new MaterialDialog.Builder(this)
                .content("要添加到个人意见模板吗？")
                .positiveText(R.string.confirm)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        mPresenter.addOpinion(opinion.getText().toString());
                        dialog.cancel();
                    }
                })
                .negativeText(R.string.cancel)
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.cancel();
                    }
                }).show();
    }

    @Override
    public void succeed() {
        RxBus.get().post("add_succeed", true);
    }

    @Override
    public void saveSuccess() {
        if (workSheet.getControl() != null && workSheet.getControl().getShowReadedButton().isShow()) {
            Map<String, String> params = new HashMap<>();
            params.put("MessageID", workSheet.getMid());
            params.put("FromNodeKey", workSheet.getNid());
            params.put("NodeKey", workSheet.getControl().getShowReadedButton().getTargetNodeKey());
            mPresenter.messageHandler(params);
        } else {
            hideDialogProgress();
            submit.setEnabled(true);
            String opinionStr = opinion.getText().toString().trim();
            startActivity(getIntent().setClass(this, StaffActivity.class).putExtra("memo", opinionStr).putExtra("workSheet", workSheet));
        }

    }

    @Override
    public void messageHandlerResult(Empl empl) {
        this.empl = empl;
        Map<String, String> params = new HashMap<>();
        params.put("memo", "");
        params.put("memoAtts", "[]");
        params.put("mid", workSheet.getMid());
        params.put("nid", workSheet.getNid());
        List<SendTarget> targets = new ArrayList<>();
        targets.add(new SendTarget(workSheet.getControl().getShowReadedButton().getTargetNodeKey(), empl.empl, "multi"));
        params.put("targets", new Gson().toJson(targets));
        mPresenter.send(params);
    }

    @Override
    public void sendSuccess() {
        //审批成功之后调用发送通知
        sendNotification();
    }

    @Override
    public void sendNotifiCationResult() {
        hideDialogProgress();
        RxBus.get().post("submitSuccess", "");
        ToastUtil.showCenter(this, R.string.submit_success);
        if (DetailActivity.from.equals("office")) {
            Intent intent = new Intent(this, OfficeActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } else if (DetailActivity.from.equals("office_new")) {
            Intent intent = new Intent(this, OfficeNewActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } else if (DetailActivity.from.equals("main")) {
            Intent intent = new Intent(this, Main.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        DetailActivity.from = "";
    }

    private void sendNotification() {
        Map<String, String> params1 = new HashMap<>();
        params1.put("mid", workSheet.getMid());
        params1.put("nodekey", workSheet.getNid());
        List<NotifyTarget> targets = new ArrayList<>();
        targets.add(new NotifyTarget(workSheet.getControl().getShowReadedButton().getTargetNodeKey(), empl == null ? "" : empl.empl));
        String nlist = new Gson().toJson(targets);
        params1.put("nlist", nlist);
        mPresenter.sendNotification(params1);
    }

    @Override
    public void requestError() {
        submit.setEnabled(true);
        hideDialogProgress();
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {
    }

    private void showDialogProgress() {
        if (progressDialog == null) {
            progressDialog = ProgressDialog.show(this, "", "正在提交");
            progressDialog.setCanceledOnTouchOutside(false);
        } else
            progressDialog.show();
    }

    private void hideDialogProgress() {
        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();
    }

    @OnClick(R.id.submit)
    public void onViewClicked() {
        String opinionStr = opinion.getText().toString().trim();
        if (TextUtils.isEmpty(opinionStr)) {
            ToastUtil.show(this, R.string.input_option_error);
            return;
        }
        showDialogProgress();
        submit.setEnabled(false);
        List<Map<String, String>> paramsList = new ArrayList<>();
        if (workSheet.getControl() != null) {
            List<WorkSheet.Cell> cells = workSheet.getControl().getSaveCell();
            if (cells != null && cells.size() > 0) {
                Gson gson = new Gson();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                for (WorkSheet.Cell cell : cells) {
                    Map<String, String> params = new HashMap<>();
                    params.put("sid", workSheet.getSid());
                    params.put("nid", workSheet.getNid());
                    params.put("row", cell.getRow());
                    params.put("col", cell.getCol());
                    if ("name".equals(cell.getType())) {
                        params.put("ival", AppApplication.getUser().EmplID);
                        params.put("val", AppApplication.getUser().EmplName);
                    } else {
                        String date = dateFormat.format(System.currentTimeMillis());
                        params.put("val", date);
                    }
                    KLog.e("savecell params:" + gson.toJson(params));
                    paramsList.add(params);
//                    mPresenter.saveMoreCell(params);
                }
            }
        }
        Map<String, String> params = new HashMap<>();
        params.put("sid", workSheet.getSid());
        params.put("nid", workSheet.getNid());
        params.put("row", workSheet.getControl().getNeedOpinion().getRow());
        params.put("col", workSheet.getControl().getNeedOpinion().getCol());
        params.put("val", opinionStr);
        params.put("ival", "");
        paramsList.add(params);
        mPresenter.saveMoreCellArrays(paramsList);


    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if(resultCode==RESULT_OK){
//            setResult(RESULT_OK);
//            finish();
//        }
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null && !disposable.isDisposed()) disposable.dispose();
        if (observable != null) {
            RxBus.get().unregister("add_opinion", observable);

        }
    }
}
